package cmd

import (
	"github.com/spf13/cobra"
	"go-programming-tour-book/tour/internal/timer"
	"log"
	"strconv"
	"strings"
	"time"
)

var calculateTime string
var duration string

// time 子命令
var timeCmd = &cobra.Command{
	Use:   "time",
	Short: "时间格式处理",
	Long:  "时间格式处理",
	Run: func(cmd *cobra.Command, args []string) {

	},
}

// time now 子命令
var nowTimeCmd = &cobra.Command{
	Use:   "now",
	Short: "获取当前时间",
	Long:  "获取当前时间",
	Run: func(cmd *cobra.Command, args []string) {
		nowTime := timer.GetNowTime()
		log.Printf("输出结果是：%s, %d\nn", nowTime.Format("2006-01-02 15:04:05"), nowTime.Unix())
		//返回两种输出格式：
		//通过调用 Format 方法输出按给定的 2006-01-02 15:04:05 格式进行格式化的时间
		//通过调用 Unix 方法返回 UNIX 时间，即时间戳，其值为自 UTC 1970年1月1日起经过的时间
	},
}

// time calc 子命令
var calculateTimeCmd = &cobra.Command{
	Use:   "calc",
	Short: "计算所需时间",
	Long:  "计算所需时间",
	Run: func(cmd *cobra.Command, args []string) {
		var currentTimer time.Time
		var layout = "2006-01-02 15:04:05"
		if calculateTime == "" {
			currentTimer = timer.GetNowTime()
		} else {
			var err error
			// strings.Count(s, str)
			// 计算字符串 str 在 s 中的非重叠个数
			space := strings.Count(calculateTime, " ")
			if space == 0 {
				layout = "2006-01-02"
			}
			if space == 1 {
				layout = "2006-01-02 15:04:05"
			}
			currentTimer, err = time.Parse(layout, calculateTime)
			if err != nil {
				t, _ := strconv.Atoi(calculateTime)
				currentTimer = time.Unix(int64(t), 0)
			}
		}
		t, err := timer.GetCalculateTime(currentTimer, duration)
		if err != nil {
			log.Fatalf("timer.GetCalculateTime er: %v\n", err)
		}

		log.Printf("输出结果：%s, %d\n", t.Format(layout), t.Unix())
	},
}
